package com.keepers.repair.adapter

import android.net.Uri
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.keepers.repair.R
import com.keepers.repair.fragment.SendMessageFragment
import com.keepers.repair.model.FileHolderModel
import org.jetbrains.anko.find

class SendResourceAdapter(val fragment: SendMessageFragment, val list: MutableList<FileHolderModel>)
    : RecyclerView.Adapter<SendResourceAdapter.ViewHolder>() {

    override fun getItemCount() = list.size + 1
    override fun onCreateViewHolder(viewGroup: ViewGroup, position: Int): ViewHolder {
        val view = LayoutInflater.from(viewGroup.context)
            .inflate(R.layout.item_send_resource, viewGroup, false)
        return ViewHolder(view)
    }
    override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
        var item: Uri? = null
        if (position < list.size) {
            item = list[position].uri
        }
        val options = RequestOptions()
            .placeholder(R.drawable.ic_add_resource_gray_50dp)
            .override(64, 64)
            .centerCrop()
        Glide.with(fragment)
            .load(item)
            .apply(options)
            .into(viewHolder.image)
        if (item == null) {
            viewHolder.remove.visibility = View.GONE
            viewHolder.remove.setOnClickListener(null)
            viewHolder.image.setOnClickListener {
                fragment.addResource()
            }
        } else {
            viewHolder.remove.visibility = View.VISIBLE
            viewHolder.image.setOnClickListener(null)
            viewHolder.remove.setOnClickListener {
                list.removeAt(position)
                notifyDataSetChanged()
            }
        }
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val image = view.find<ImageView>(R.id.item_send_resource_image)
        val remove = view.find<ImageButton>(R.id.item_send_resource_remove)
    }
}
